package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: WackyBoy
 * @Date: 2021/6/29 19:55
 */

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;

    @Autowired
    StringRedisTemplate redisTemplate;


    @GetMapping({"/", "index.html"})
    public String indexPage(Model model) {
        // TODO: 查出所有的1级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("catagory", categoryEntities);

        return "index";
    }

    //"index/catalog.json"
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String Hello() {
        // 1. 获取一把锁, 只要锁的名字一样, 就是同一把锁
        RLock lock = redisson.getLock("my-lock");

        // 2. 加锁
//        lock.lock();        // 阻塞式等待, 进入AQS队列排序, 等待被唤醒, 默认加的锁都是30秒
        // 1) watch dog(看门狗): 锁的自动续期, 如果业务超长, 运行期间主动给锁续上新的30s. 不用担心业务时间长, 锁自动过期被删掉
        // 2) 加锁的业务只要运行完成, 就不会给当前续期, 即使不手动解锁, 锁默认在30s以后自动删除

        lock.lock(10, TimeUnit.SECONDS);    // 10秒自动解锁, 自动解锁时间一定要大于业务的执行时间
        // 问题: lock.lock(10, TimeUnit.SECONDS); 在锁时间到了以后, 不会自动续期
        // 1. 如果我们指定了锁的超时时间, 就发送给redis执行脚本, 进行占锁, 默认超时就是我们指定的时间
        // 2. 如果我们未指定锁的超时时间, getLockWatchdogTimeout(30 * 1000ms)
        //      只要占锁成功, 就会启动一个定时任务[重新给锁设置过期时间, 新的过期时间==>getLockWatchdogTimeout]
        //      this.internalLockLeaseTime / 3L[三分之一的看门狗时间后, 自动续期]

        // 最佳实战:
        // 1)  lock.lock(30, TimeUnit.SECONDS);   省掉整个续期操作, 手动解锁
        try {
            Thread.sleep(30000);
            System.out.println("加锁成功, 执行业务!" + Thread.currentThread().getId());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 3. 解锁
            System.out.println("释放锁" + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }



    // 保证一定能读到最新数据, 修改期间, 写锁是一个排他锁(互斥锁, 独享锁). 读锁是一个共享锁
    // 写锁没释放, 读必须等待
    // 写+ 读: 等待写锁释放
    // 写+ 写: 阻塞
    // 读 + 写:
    // 读 + 读: 相当于无锁模式, 并发读, 只会在redis中记录好所有当前的读锁, 同时加锁成功(为啥我的不是??? ==> 使用不同的浏览器)
    @ResponseBody
    @GetMapping("/write")
    public String writeValue() {

        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.writeLock();
        try {
            rLock.lock();
            // 改数据, 加写锁, 读数据, 加读锁
            s = UUID.randomUUID().toString();
            System.out.println("写锁加锁成功!" + Thread.currentThread().getId());
            redisTemplate.opsForValue().set("writeValue", s);
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }

        return s;
    }

    @ResponseBody
    @GetMapping("/read")
    public String readValue() {
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.readLock();
        try {
            rLock.lock();
            System.out.println("读锁加锁成功!" + Thread.currentThread().getId());
            s = redisTemplate.opsForValue().get("writeValue");
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }

        return s;
    }

    /**
     * 模拟车库停车
     * 信号量也可以用作信号量限流
     */

    @ResponseBody
    @GetMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
//        park.acquire();     // 获取一个值(信号), 阻塞方法
        boolean b = park.tryAcquire();
        if(b) {
            // 执行业务
        } else {
            return "error";
        }

        return "OK" + b;
    }

    @ResponseBody
    @GetMapping("/go")
    public String go() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        park.release();     // 释放一个信号

        return "go";
    }

    /**
     * 放假: 锁门
     * 5个班全部走完, 才可以锁大门
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch countDownLatch = redisson.getCountDownLatch("door");
        countDownLatch.trySetCount(5);
        countDownLatch.await();

        return "放假了";
    }

    @ResponseBody
    @GetMapping("gogogo/{id}")
    public String gogogo(@PathVariable("id") Long id) {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();   // 计数减一
        return id + "班的人都走了...";
    }


}
